/// <reference path="phaser.js" />
XMas.Game = function(game){
};

XMas.Game.prototype = {
    initialize:function(){
        XMas.scoreText = null;
        XMas.score = 0;
        XMas.item_keyIDs = new Array();
        XMas.item_items = [];
        XMas.item_count = 0;
        XMas.santa_count = 0;
        XMas.santa_items = [];
        XMas.santa_keyIDs =  new Array();
        XMas.santa_timers = [];
        XMas.gift_group  = null;
        XMas.gift_max = 0;
        XMas.gift_i = 0;
        XMas.gift_numberOfGiftPerDropdown = 0;
        XMas.level_nextScore = 0;
        XMas.GlobalVariables.LEVEL_CURRENT=null;
        XMas.GlobalVariables.LEVEL_CURRENT_NO=1;
        XMas.item_requestedItemList = [];
        XMas.isSound = true;
    },
    create: function () {
        this.initialize();
        //level
        XMas.GlobalVariables.LEVEL_CURRENT = XMas.Config.Levels[0];
        // start the physics engine
        this.physics.startSystem(Phaser.Physics.ARCADE);
        // display images: background, floor and score
        this.add.sprite(0, 0, 'backgroundMain');
        //Snow
        XMas.Snow.prototype.initialize(this);
        //score
        var fontStyle = { font: "38px Arial", fill: "WHITE",align: "center" };
        XMas.scoreText = this.add.text( 
            XMas.GlobalVariables.GAME_WIDTH/2-20,
            17,XMas.score.toString(),fontStyle);
        //item
        this.add.sprite(30,110,'res_item_shell');
        for(var i =0;i<5;i++){
             XMas.Item.createItem(this);
        }
        //santa
       for(var i=0;i<XMas.GlobalVariables.LEVEL_CURRENT.santaNumber;i++){
            XMas.Santa.createSanta(this);
        }
        //gift
        XMas.gift_group = this.add.group();
        XMas.Gift.initialize(this);
        //transition page
        var blackFade = this.add.sprite(0, 0, "blackfade");
        XMas.Effect.transitionPage(blackFade, 2000, 0, this);
        this.time.events.loop(Phaser.Timer.SECOND * 3,function(){
                XMas.isSound = true;
        },this);
    },
    update:function(){
        XMas.Gift.changeWindDirection();
        XMas.Snow.prototype.changeWindDirection();
        XMas.Level.prototype.update(this);
        this.world.bringToTop(XMas.gift_group);

    }
}

XMas.Score ={
    plus : function(game,score,isSantaReceiveItem){
        XMas.score+=parseInt(score);
        this.updateScoreText(game,score,isSantaReceiveItem);
    },
    substract:function(game,score,isSantaReceiveItem){
        score = parseInt(score);
        if(XMas.score>=score)
            XMas.score -= score;
        else XMas.score = 0;
        this.updateScoreText(game,-(score),isSantaReceiveItem);
    },
    muiltifly: function(game,score,percentage,isSantaReceiveItem){
        score = parseInt(score);
        XMas.score += Math.round(XMas.score * percentage / 100);
        this.updateScoreText(game,Math.round(XMas.score * percentage / 100),isSantaReceiveItem);
    },
    divide: function(game,score, percentage,isSantaReceiveItem){
      score = parseInt(score);
      XMas.score -= Math.round(XMas.score * percentage / 100);  
      this.updateScoreText(game,-(Math.round(XMas.score * percentage / 100)),isSantaReceiveItem);
    },
    updateScoreText : function(game,fakeScore,isSantaReceiveItem){
        XMas.scoreText.text = XMas.score.toString();
        XMas.Effect.updateScore(game,fakeScore,isSantaReceiveItem);
        var score = parseInt(XMas.score);
        if(score==0){
            XMas.scoreText.x = XMas.GlobalVariables.GAME_WIDTH/2-20;
              return;
        }
        if(score<100)
        {
            XMas.scoreText.x = XMas.GlobalVariables.GAME_WIDTH/2-30;
            return;
        }
        if(score<1000)
        {
            XMas.scoreText.x = XMas.GlobalVariables.GAME_WIDTH/2-40;
            return;
        }
        if(score<10000)
        {
            XMas.scoreText.x = XMas.GlobalVariables.GAME_WIDTH/2-50;
            return;
        }
        if(score<100000)
        {
            XMas.scoreText.x = XMas.GlobalVariables.GAME_WIDTH/2-60;
            return;
        }
    }
}

XMas.Item = {
    createItem : function(game){
        var notExistItemKeyId = game.rnd.integerInRange(1,8);
        while(XMas.item_keyIDs.indexOf(notExistItemKeyId)!=-1){
            notExistItemKeyId = game.rnd.integerInRange(1,8);
        }
        XMas.item_keyIDs.push(notExistItemKeyId);
        var itemConfig = XMas.Config.items[notExistItemKeyId-1];
        XMas.item_count++;
        var item = game.add.sprite(0,0,'res_item_'+itemConfig.keyID);
        item.keyID = itemConfig.keyID;
        item.width =  XMas.GlobalVariables.ITEM_WIDTH;
        item.height =  XMas.GlobalVariables.ITEM_HEIGHT;
        item.inputEnabled = true;
        item.input.enableDrag(false,false);
        item.events.onDragStart.add(this.onDrag,this);
        item.events.onDragStop.add(function(){XMas.Item.onDrop(game,item)},this);
        XMas.item_items[itemConfig.keyID] = item;
        XMas.item_items[itemConfig.keyID].object = itemConfig;
        this.updateItemCordinator(XMas.item_count);
        //effect
        XMas.Effect.itemAppear(game,item);
    },
     calculateXCordinator : function(index,total){
       var marginLeft = (XMas.GlobalVariables.ITEM_REGIONWIDTH/ (total+1));
        return (marginLeft  * index - XMas.GlobalVariables.ITEM_WIDTH / 2); 
    },
     updateItemCordinator:function(numberOfItems){
        var index = 1;
        var x = 0;
        XMas.item_keyIDs.forEach(function(keyID){
            x= XMas.Item.calculateXCordinator(index++,XMas.item_keyIDs.length);
            XMas.item_items[keyID].x = x + 25 ;
            XMas.item_items[keyID].y = XMas.GlobalVariables.ITEM_MARGINTOP;
            XMas.item_items[keyID].bk_x = XMas.item_items[keyID].x;
            XMas.item_items[keyID].bk_y = XMas.item_items[keyID].y;
        });
    },
    onDrag : function(item)
    {
        item.bringToTop();
    },
    onDrop:function(game,item){
        var isOverlapCorrectSanta = this.checkOverlapOnSanta(game,item);
         XMas.Effect.itemOnDrop(game,item,isOverlapCorrectSanta);
    },
    checkOverlapOnSanta : function(game,item){
        var result = false;
         var boundItem= item.getBounds();
         var boundSanta;
         XMas.santa_keyIDs.forEach(function(keyID){
             boundSanta = XMas.santa_items[keyID].getBounds();
            if(Phaser.Rectangle.intersects(boundItem,boundSanta)){
               result  = XMas.santa_items[keyID].ReceiveGift(item.keyID);
               XMas.Effect.santaEmotion(game,XMas.santa_items[keyID]);
            } 
         });
         return result;
     }
}

XMas.Santa = {
    createSanta : function(game){
        var notExistSantaKeyId = game.rnd.integerInRange(1,4);
        while(XMas.santa_keyIDs.indexOf(notExistSantaKeyId)!=-1){
            notExistSantaKeyId = game.rnd.integerInRange(1,4);
        }
        XMas.santa_keyIDs.push(notExistSantaKeyId);
        var itemConfig = XMas.Config.santas[notExistSantaKeyId-1];
        var santa = game.add.sprite(0,0,'res_santa_'+itemConfig.keyID);
        var thinking  = game.add.image(0,0,'res_common_thinking');
        var patient  = game.add.sprite(0,0,'res_santa_patient');
        var fontStyle = { font: "13px Arial", fill: "WHITE", align: "center" };
        var santaName = game.add.text(0,0,itemConfig.name,fontStyle);
        patient.frame = parseInt(itemConfig.patient)-1;
        thinking.width = 100;
        thinking.height = 100;
        thinking.visible = false;
        XMas.santa_items[itemConfig.keyID] = santa;
        XMas.santa_items[itemConfig.keyID].object = itemConfig;
        XMas.santa_items[itemConfig.keyID].thinking = thinking;
        XMas.santa_items[itemConfig.keyID].patient = patient;
        XMas.santa_items[itemConfig.keyID].patient.score = itemConfig.patient;
        XMas.santa_items[itemConfig.keyID].santaName = santaName;
        XMas.santa_items[itemConfig.keyID].ReceiveGift = function(giftID)
        {
            return XMas.Santa.receiveGift(game,itemConfig.keyID,giftID);
        }
        XMas.santa_count++;
        this.updateSantasCordinator(XMas.santa_count);
        XMas.santa_timers[itemConfig.keyID] =  game.time.events.add(Phaser.Timer.SECOND * itemConfig.timeDelay, this.requestGift, this,game,itemConfig.keyID);
    },
    updateLevel:function(game){
        XMas.backgroundLevelUp.play('', 0, 1, false);
        var textLevelUp = game.add.text(game.world.centerX, game.world.centerY, "Level Up");

        //  Centers the text
        textLevelUp.anchor.set(0.5);
        textLevelUp.align = 'center';
        //  Our font + size
        textLevelUp.font = 'Arial';
        textLevelUp.fontSize = 35;
        textLevelUp.fill = '#ffff00';
        game.add.tween(textLevelUp).to({ alpha: 0 }, 1000, Phaser.Easing.Linear.None, true);
        game.add.tween(textLevelUp).to({ fontSize: 100 }, 1000, Phaser.Easing.Linear.None, true);
        
        XMas.santa_keyIDs.forEach(function(keyID){
            if(XMas.santa_items[keyID].object.timeRequest>2){
            XMas.santa_items[keyID].object.timeRequest-= parseInt(XMas.GlobalVariables.LEVEL_CURRENT.timeRequest);
            }
            if(XMas.santa_items[keyID].object.timeRequest<2)
                iXMas.santa_items[keyID].object.timeRequest=2;

            if(XMas.santa_items[keyID].object.timeDelay>2){
                XMas.santa_items[keyID].object.timeDelay-=parseInt(XMas.GlobalVariables.LEVEL_CURRENT.timeDelay);
            }
            if(XMas.santa_items[keyID].object.timeDelay<2)
                    XMas.santa_items[keyID].object.timeDelay = 2;
        });
        for(var i = XMas.santa_count;i<XMas.GlobalVariables.LEVEL_CURRENT.santaNumber;i++){
            this.createSanta(game);
        }
    },
    receiveGift : function(game,keyID,giftID){
        var result = false;
        if(!XMas.santa_items[keyID].IsRequesting){
            return result;
        }
        if(XMas.santa_timers[keyID]!=null){
            game.time.events.remove(XMas.santa_timers[keyID]);
        }
        if(XMas.santa_items[keyID].RequestedGiftId===giftID){
            result  = true;
            XMas.Score.plus(game,XMas.item_items[giftID].object.score,true);
            XMas.Santa.increasePatient(game,keyID,true);
        }
        else{
            result = false;
            XMas.Score.substract(game,XMas.item_items[giftID].object.score,true);
            XMas.Santa.increasePatient(game,keyID,false);
        }
        if(parseInt(XMas.item_requestedItemList[giftID])!=0)
            XMas.item_requestedItemList[giftID] = parseInt(XMas.item_requestedItemList[giftID])-1; 
        XMas.Santa.registerRequestGift(game,keyID);
        return result;
    },
    requestGift:function(game,keyID){
            //var rdGiftId = game.rnd.integerInRange(1,XMas.item_count);
            var rdGiftId = XMas.item_keyIDs[Math.floor(Math.random() * XMas.item_keyIDs.length)];
            if(XMas.item_requestedItemList[rdGiftId]!=null){
                while(XMas.item_requestedItemList[rdGiftId]==1)
                {
                    rdGiftId = XMas.item_keyIDs[Math.floor(Math.random() * XMas.item_keyIDs.length)];
                }
                XMas.item_requestedItemList[rdGiftId] = parseInt(XMas.item_requestedItemList[rdGiftId]) + 1;
            }
            else{
                XMas.item_requestedItemList[rdGiftId] = 1;
            }
            var giftConfig = XMas.Config.items[rdGiftId-1];
            XMas.Effect.thinkingBeginRotation(game,XMas.santa_items[keyID],XMas.santa_items[keyID].thinking);
            var requestedGift = game.add.image(XMas.santa_items[keyID].x+90,
                XMas.GlobalVariables.SANTA_MARGINTOP - 60,
                'res_item_'+giftConfig.keyID);
            requestedGift.scale.setTo(0.8,0.8);
            XMas.santa_items[keyID].requestedGift = requestedGift;
            XMas.Effect.requestedGiftAppear(game,requestedGift,keyID);
            game.time.events.remove(XMas.santa_timers[keyID]);
            XMas.santa_items[keyID].RequestedGiftId = giftConfig.keyID;
            XMas.santa_items[keyID].IsRequesting = true;
            XMas.santa_timers[keyID] = game.time.events.add(Phaser.Timer.SECOND * XMas.santa_items[keyID].object.timeRequest, this.requestTimeOut,this,game,keyID,giftConfig.keyID,giftConfig.score);
    },
    requestTimeOut : function(game,keyID,giftId,score){
        if(parseInt(XMas.item_requestedItemList[giftId])!=0)
            XMas.item_requestedItemList[giftId] = parseInt(XMas.item_requestedItemList[giftId])-1; 
       XMas.Score.substract(game,score,true);
       XMas.Santa.increasePatient(game,keyID,false);
       XMas.Santa.registerRequestGift(game,keyID);
    },
    registerRequestGift : function(game,keyID){
        XMas.santa_items[keyID].IsRequesting = false;
        XMas.santa_items[keyID].thinking.visible = false;
         if(XMas.santa_items[keyID].requestedGift!=null){
             XMas.santa_items[keyID].requestedGift.destroy();
        }
        game.time.events.remove(XMas.santa_timers[keyID]);
        if(XMas.santa_count==1){
            XMas.santa_timers[keyID] = game.time.events.add(Phaser.Timer.SECOND * 2, this.requestGift,this,game,keyID);
        }
        else{
            XMas.santa_timers[keyID] = game.time.events.add(Phaser.Timer.SECOND * XMas.santa_items[keyID].object.timeDelay, this.requestGift,this,game,keyID);
        }
    },
    increasePatient:function(game,keyID,isIncrease){
        if(isIncrease && parseInt(XMas.santa_items[keyID].patient.score)>=XMas.GlobalVariables.SANTA_MAXPATIENT){
            if(XMas.isSound){
                XMas.santa_Correct[game.rnd.integerInRange(1,8)].play('', 0, 1, false);
                XMas.isSound = false;
            }
            XMas.Effect.santaEmotion(game,XMas.santa_items[keyID]);
            return;
        }
        if(isIncrease){
            XMas.santa_items[keyID].patient.score = parseInt(XMas.santa_items[keyID].patient.score) +1;
            if(XMas.isSound){
                XMas.santa_Correct[game.rnd.integerInRange(1,8)].play('', 0, 1, false);
                XMas.isSound = false;
            }
        }
        else{
            XMas.santa_items[keyID].patient.score  = parseInt(XMas.santa_items[keyID].patient.score)-1;
            if(XMas.isSound){
                XMas.santa_Incorrect[game.rnd.integerInRange(1,6)].play('', 0, 1, false);
                XMas.isSound = false;
            }
        }
          if(parseInt(XMas.santa_items[keyID].patient.score)==0){
              XMas.backgroundMusic.destroy();
              game.state.start('GameOver', true, false);
             
              
            return;
        }
        else{
            if(parseInt(XMas.santa_items[keyID].patient.score)>0){
                XMas.santa_items[keyID].patient.frame = parseInt(XMas.santa_items[keyID].patient.score) - 1;
            }
            XMas.Effect.santaEmotion(game,XMas.santa_items[keyID]);
        }
        return;
    },
    calculateXCordinator : function(index,total){
       var marginLeft = (XMas.GlobalVariables.SANTA_REGIONWIDTH/ (total+1));
        return (marginLeft  * index - XMas.GlobalVariables.SANTA_WIDTH / 2); 
    },

    updateSantasCordinator:function(numberOfSantas){
        var index = 1;
        var x = 0;
        XMas.santa_keyIDs.forEach(function(keyID){
            x= XMas.Santa.calculateXCordinator(index++,XMas.santa_keyIDs.length);
            XMas.santa_items[keyID].x = x + (index*30)-80;
            XMas.santa_items[keyID].y = XMas.GlobalVariables.SANTA_MARGINTOP;
            XMas.santa_items[keyID].santaName.x = XMas.santa_items[keyID].x+50;
            XMas.santa_items[keyID].santaName.y = XMas.GlobalVariables.SANTA_MARGINTOP + 100 ;
            XMas.santa_items[keyID].thinking.x = XMas.santa_items[keyID].x+65.5;
            XMas.santa_items[keyID].thinking.y = XMas.GlobalVariables.SANTA_MARGINTOP - 73.5;
            XMas.santa_items[keyID].patient.x = XMas.santa_items[keyID].x +40;
            XMas.santa_items[keyID].patient.y = XMas.GlobalVariables.SANTA_MARGINTOP + 200;
            if(XMas.santa_items[keyID].requestedGift!=null){
                XMas.santa_items[keyID].requestedGift.x = XMas.santa_items[keyID].x+90;
                XMas.santa_items[keyID].requestedGift.y = XMas.GlobalVariables.SANTA_MARGINTOP -50;
            }
        });
        
    }
}

XMas.Gift = {
    initialize: function(game){
        game.time.events.loop(Phaser.Timer.SECOND * 15,this.createGift,this,game);
    },
    createGiftLoop:function(game){
    game.time.events.repeat(Phaser.Timer.SECOND * 1,game.rnd.integerInRange(1,3),this.createGift,this,game);
    },
    createGift:function(game){
        var rdPresentId  = 0;
        while(rdPresentId<1 || rdPresentId>30){
            rdPresentId= game.rnd.integerInRange(1,30);
        }
        var gift = this.loadGift(1);
        switch(rdPresentId){
            case 1:
            case 3:
            case 4:
            case 5:
            case 7:
            case 6:
            case 9:
            case 11:
            case 13:
            case 15:
            case 16:
            case 17:
            case 19:
            case 21:
            //hopeful star
            gift = this.loadGift(1);
            break;
            case 2:
            case 8:
            case 12:
            case 14:
            case 18:
            //bug
            gift = this.loadGift(2);
            break;
            case 22:
            case 24:
            //NC
            gift = this.loadGift(3);
            break;
            case 7:
            //bomb
            gift = this.loadGift(4);
            break;
            case 23:
            case 25:
            case 26:
            case 27:
            case 28:
            case 30:
            //promotion
            gift = this.loadGift(5);
            break;
            case 10:
            case 20:
            case 29:
            //item
            if(XMas.item_count==8){
                gift = this.loadGift(1);
            }
            else{
                switch(rdPresentId){
                    case 10:
                        gift = this.loadGift(6);
                    break;
                    case 20:
                        gift = this.loadGift(2);
                    break;
                    case 29:
                        gift = this.loadGift(1);
                    break;
                }
            }
            break;
        }
        //var item  = XMas.gift_group.create(game.rnd.integerInRange(50,400),-30,'res_gift_'+gift.keyID);
        var rndGift = game.rnd.integerInRange(1,4);
        var resGift = 'res_gift_green_spritesheet';
        switch(rndGift){
            case 1:
            resGift = 'res_gift_green_spritesheet';
            break;
            case 2:
            resGift = 'res_gift_pink_spritesheet';
            break;
            case 3:
            resGift = 'res_gift_violet_spritesheet';
            break;
             case 4:
            resGift = 'res_gift_red_spritesheet';
            break;
        }
        var item  = XMas.gift_group.create(game.rnd.integerInRange(50,400),-30,resGift);
        game.physics.enable(item, Phaser.Physics.ARCADE);
        var rndScale = game.rnd.realInRange(0.7,1.2);
        item.scale.setTo(rndScale,rndScale);
        item.body.gravity.y = 0;
        item.body.velocity.y += game.rnd.integerInRange(100,100);
        item.body.velocity.x += game.rnd.integerInRange(-50,50);
        item.inputEnabled  = 'true';
        item.object = gift;
        item.events.onInputDown.add(function(){XMas.Gift.onClick(game,item,gift)}, this);
        item.events.onOutOfBounds.add(function(){item.kill();}, this);
        item.checkWorldBounds = true;
        //effect
        XMas.Effect.giftFallDown(game,item);
    },
    loadGift:function(type){
        return XMas.Config.giftItems[type-1];
    },
    onClick : function(game,item,gift){
        XMas.Effect.giftClicked(game,item);
        XMas.gift_clickedSound[item.object.keyID].play('', 0, 1, false);
        item.destroy();
        switch(gift.type){
            case '1':
            XMas.Score.plus(game,gift.score,false);
            break;
            case '2':
            XMas.Score.substract(game,gift.score,false);
            break;
            case '3':
            XMas.Score.divide(game,XMas.score,gift.score,false);
            break;
            case '4':
             XMas.santa_keyIDs.forEach(function(key){
                var score = parseInt(XMas.santa_items[key].patient.score);
                if(score>1){
                    XMas.santa_items[key].patient.score  = score - 1;
                }
            });
            break;
            case '5':
            XMas.Score.muiltifly(game,XMas.score,gift.score,false);
            break;
            case '6':
            XMas.Item.createItem(game);
            break;
        }
    },
    changeWindDirection : function() {
        XMas.gift_i++;
        if (XMas.gift_i === XMas.GlobalVariables.GIFT_UPDATE_INTERVAL)
        {
              var multi = Math.floor((XMas.gift_max + 200) / 4),
                frag = (Math.floor(Math.random() * 100) - multi);
                XMas.gift_max = XMas.gift_max + frag;
                if (XMas.gift_max > 200) XMas.gift_max = 200;
                if (XMas.gift_max < -200) XMas.gift_max = -200;
                XMas.Gift.setXSpeed(XMas.gift_max);
            XMas.GlobalVariables.GIFT_UPDATE_INTERVAL = Math.floor(Math.random() * 20) * 60; // 0 - 20sec @ 60fps
            XMas.gift_i = 0;
        }
    },
    setXSpeed : function(max) {
        XMas.gift_group.forEach(function(item){
           item.body.velocity.x -=  XMas.gift_max - Math.floor(Math.random() * 30);
           item.body.velocity.y +=  50;
        });
    }
}

XMas.Level = function(game){

}

XMas.Level.prototype={
     update: function(game){
        if(XMas.GlobalVariables.LEVEL_CURRENT_NO<6){
            if(XMas.score>parseInt(XMas.GlobalVariables.LEVEL_CURRENT.toScore)){
                XMas.GlobalVariables.LEVEL_CURRENT_NO++;
                 if(XMas.item_count<8){
                    XMas.Item.createItem(game);
                    }
                XMas.GlobalVariables.LEVEL_CURRENT = XMas.Config.Levels[XMas.GlobalVariables.LEVEL_CURRENT_NO-1];
                XMas.Santa.updateLevel(game);
            }
            if(XMas.GlobalVariables.LEVEL_CURRENT_NO==5){
                XMas.level_nextScore = parseInt(XMas.GlobalVariables.LEVEL_CURRENT.toScore)+parseInt(XMas.Config.Levels[5].score);
            }
        }
        else{
            if(XMas.score>XMas.level_nextScore){
                XMas.level_nextScore +=parseInt(XMas.GlobalVariables.LEVEL_CURRENT.score);
                XMas.Santa.updateLevel(game);
            }
        }
    }
}

XMas.Effect={
    itemAppear : function(game,item){
        game.add.tween(item).from( { y: -50 }, 1500, Phaser.Easing.Bounce.Out, true);
    },
    itemBackToShell:function(game, item){
        var tw = game.add.tween(item);
        tw.to({ x: item.bk_x,y:item.bk_y,alpha:0.1 }, 200, Phaser.Easing.Linear.None);
        tw.onComplete.addOnce(function(){item.alpha=1;}, this);
        tw.start();
        var tw2 = game.add.tween(item.scale);
        tw2.to({ x:1.1,y:1.1 }, 200, Phaser.Easing.Linear.None);
        tw2.start();
    },
    itemOnDrop:function(game,item,isOverlapSanta){
        if(isOverlapSanta){
        var tw = game.add.tween(item.scale).to( { x: 0.1,y:0.1}, 100, Phaser.Easing.Linear.None,true);
        tw.onComplete.addOnce(function(){this.itemBackToShell(game,item);},this);
        tw.start();
        }
        else{
            this.itemBackToShell(game,item);
        }
    },
    thinkingBeginRotation:function(game,santa,item)
    {
       
    },
    requestedGiftAppear : function(game,gift,keyID){
        //var tw = game.add.tween(gift.scale).from( { x: 0.1,y:0.1}, 200, Phaser.Easing.Linear.None,true);
        //tw.onComplete.addOnce(function(){XMas.santa_items[keyID].thinking.visible = true;},this);
        //tw.start();
        XMas.santa_items[keyID].thinking.visible = true;
    },
    giftFallDown:function(game, gift){
          gift.animations.add('falldown');
          gift.animations.killOnComplete = true;
          gift.animations.play('falldown', 5, true);
    },
    santaEmotion:function(game, santa){
        var patient = santa.patient.score;
        var spriteSheet;
        switch (patient){
            case 2:
             sprite = [16,17,18,19,20,21,22,23];
             break;
             case 1:
             sprite = [24,5,26,27,28,29,30,31];
             break;
             case 3:
             sprite = [6,7,8,9,10,11,12,13];
             break;
             case 4:
             sprite = [0,1,2,3,4,5,6,7];
             break;
             default:
             sprite = [32,33,34,35,36,37,38,39];
             break;
        }
          var anim = santa.animations.add('emotion',sprite,true);
          anim.play(18, true);
          anim.onLoop.add(this.animationLooped, this);
    },
    animationLooped : function(sprite, animation) {
        if (animation.loopCount === 1) {
            animation.loop = false;
        }
    },
    updateScore:function(game,score,isReceiveItem){
        if(isReceiveItem==false){
              var fontStyle = { font: "38px Arial", fill: "YELLOW", align: "center" };
        var fakeScore  = game.add.text(XMas.scoreText.x,XMas.scoreText.y,score,fontStyle);
            var tw = game.add.tween(fakeScore);
            tw.from({x: game.input.activePointer.x, y:game.input.activePointer.y}, 500, Phaser.Easing.Linear.None);
            tw.onComplete.addOnce(function(){fontStyle = null;fakeScore.destroy();}, this);
            tw.start();
            var tw2 = game.add.tween(fakeScore.scale);
            tw2.from({x: 3, y:3}, 500, Phaser.Easing.Linear.None);
            tw2.start();
        }
        else{
            var tw = game.add.tween(XMas.scoreText);
            tw.to({fontSize:42},100);
            tw.onComplete.addOnce(function(){
                var tw2 = game.add.tween(XMas.scoreText).to({fontSize:38},100);
                tw2.start();
            },this);
            tw.start();
        }
    },
    giftClicked:function(game, gift){
        var explosion = game.add.sprite(game.input.activePointer.x, game.input.activePointer.y, 'res_gift_explosion_' + gift.object.keyID);
        explosion.anchor.setTo(0.5, 0.5);
        // Add an animation for the explosion that kills the sprite when the
        // animation is complete
        var animation = explosion.animations.add('boom', [0, 1, 2, 3, 4, 5], 30, false);
        var animationBack = explosion.animations.add('boomBack', [5,4,3,2,1,0], 60, false);
        animation.onComplete.add(function(){
            game.time.events.add(400, function(){
                explosion.animations.play('boomBack');
            });
        },this);
        animationBack.onComplete.add(function(){
            explosion.kill();
        },this);

        animationBack.killOnComplete = true;
        // Move the explosion to the given coordinates
        explosion.x = game.input.activePointer.x;
        explosion.y = game.input.activePointer.y;
        // Set rotation of the explosion at random for a little variety
        //explosion.angle = game.rnd.integerInRange(0, 360);
        // Play the animation
        explosion.animations.play('boom');
    },
    //obj     : This is a sprite or image obj
    //speed   : This is speed to run a effect of obj
    //opacity : The obj is transparent if set 0 , obj is appear if set 1
    //bootObj : This is a game obj of phaser
    transitionPage: function(obj, speed, opacity, bootObj) {
        var fadeTween = bootObj.add.tween(obj);
        fadeTween.to({
            alpha: opacity
        }, speed, Phaser.Easing.Linear.Out, true);
    },
    //obj     : This is a sprite or image obj
    //speed   : This is speed to run a effect of obj
    //opacity : The obj is transparent if set 0 , obj is appear if set 1
    //bootObj : This is a game obj of phaser
    //toX     : To scale obj to x
    //toY     : To scale obj to y
    effectMultipleTween: function(obj, speed, opacity, bootObj, toX, toY) {
        XMas.Effect.transitionPage(obj, speed, opacity, bootObj);
        var scaleObj = bootObj.add.tween(obj.scale);
        scaleObj.to({ x: toX, y: toY }, speed - 1000, Phaser.Easing.Linear.Out, true);
    },
    //bootObj : This is a game obj of phaser
    //obj     : This is a sprite or image obj
    timeWaitAnotherEffect: function(bootObj, obj) {
        XMas.Effect.effectMultipleTween(obj, 2000, 1, bootObj, 1, 1);
    }
}

XMas.Snow = function (game) {
    this.snow_emitter_group;
    this.update_interval = 4 * 60;
    this.update_interval_counter = 0;
}

XMas.Snow.prototype = {
    initialize:function(game){
        this.snow_emitter_group = game.add.group();

        var back_emitter = game.add.emitter(game.world.centerX, -32, 600);
        back_emitter.makeParticles('res_snowflakesImg', [0, 1, 2, 3, 4, 5 ,6,7]);
        back_emitter.maxParticleScale = 0.6;
        back_emitter.minParticleScale = 0.2;
        back_emitter.setYSpeed(20, 100);
        back_emitter.gravity = 0;
        back_emitter.width = game.world.width * 1.5;
        back_emitter.minRotation = 0;
        back_emitter.maxRotation = 40;
        this.snow_emitter_group.add(back_emitter);

        var mid_emitter = game.add.emitter(game.world.centerX, -32, 250);
        mid_emitter.makeParticles('res_snowflakesImg', [0, 1, 2, 3, 4, 5,6,7]);
        mid_emitter.maxParticleScale = 0.5;
        mid_emitter.minParticleScale = 0.5;
        mid_emitter.setYSpeed(50, 150);
        mid_emitter.gravity = 0;
        mid_emitter.width = game.world.width * 1.5;
        mid_emitter.minRotation = 0;
        mid_emitter.maxRotation = 40;
        this.snow_emitter_group.add(mid_emitter);

        this.changeWindDirection();

        back_emitter.start(false, 14000, 300);
        mid_emitter.start(false, 12000, 500);
    },
    changeWindDirection:function(){
        if(this.update_interval_counter ===0 || this.update_interval_counter === this.update_interval){
            var multi = Math.floor((XMas.GlobalVariables.WIND_SPEED_MAX + 200) / 4);
            var frag = (Math.floor(Math.random() * 100) - multi);
            XMas.GlobalVariables.WIND_SPEED_MAX += frag;
            if (XMas.GlobalVariables.WIND_SPEED_MAX > 200) {
                XMas.GlobalVariables.WIND_SPEED_MAX = 150;
            }
            if (XMas.GlobalVariables.WIND_SPEED_MAX < -200) {
                XMas.GlobalVariables.WIND_SPEED_MAX = -150;
            }
            this.snow_emitter_group.forEach(function(item){
                item.forEachAlive(function(emitter){
                    emitter.body.velocity.x = XMas.GlobalVariables.WIND_SPEED_MAX - Math.floor(Math.random() * 30);
                });
            });
            this.update_interval = Math.floor(Math.random() * 20) * 60; // 0 - 20sec @ 60fps
            this.update_interval_counter = 0;
        }
        this.update_interval_counter++;
    }
}

XMas.Util={
    getBestScore: function (game) {
        XMas.bestScore = 0;
        var httpRequest = new XMLHttpRequest;
        httpRequest.onreadystatechange = function() {
            if (httpRequest.readyState === 4) { // request is done
                if (httpRequest.status === 200) { // successfully
                    // alert(httpRequest.responseText); // we're calling our method
                    if (XMas.score > parseInt(httpRequest.responseText)) {
                        XMas.bestScore = XMas.score;
                        //call Post Data to server
                    } else {
                         XMas.bestScore = httpRequest.responseText;
                     }
                     //XMas.backgroundMusic.destroy();
                     //game.state.start('GameOver', true, false);
                }
            }
        };
        httpRequest.open('GET', "http://masamuri-001-site9.smarterasp.net/api/game");
        httpRequest.send();
    },
    postBestScore: function () {
        //this method doesn't work because the issue from api
        var httpRequest = new XMLHttpRequest;
        //var params = "score=100";
        httpRequest.open('POST', "http://masamuri-001-site9.smarterasp.net/api/game?score=" + XMas.score.toString(), true);
        //httpRequest.setRequestHeader("Content-Type", "application/json");
        httpRequest.send();
        

    }
}